<template>
  <div>
    <el-dialog
      title="发布动态"
      :visible.sync="visible"
      width="820px"
      append-to-body
    >
      <avue-form
        ref="addform"
        v-model="form"
        :option="dynamicOption"
        :upload-change="$uploadChange"
        :upload-exceed="uploadExceed"
        :upload-before="uploadBefore"
        :upload-error="uploadSizeError"
      >
        <!--关联账号-->

        <template #name>
          <el-select
            v-model="form.name"
            filterable
            :disabled="editId !== ''"
            @change="changeName"
          >
            <el-option
              v-for="item in list"
              :key="item.userId"
              :label="item.label"
              :value="item.userId"
            ></el-option>
          </el-select>
        </template>
        <!--标签-->
        <template #tag>
          <div>
            <span
              v-for="(item, index) in tagList"
              :key="index"
              :class="[
                toggleList.map((e) => e.id).includes(item.id) ? 'selected' : '',
                'sub-item',
              ]"
              @click="select(item)"
            >
              {{ item.label }}
            </span>
          </div>
          <!-- <div>
            <el-tag
              v-for="(item,index) in tagList"
              :key="index"
              size="medium"
              class="tags-item"
            >{{ item.name }}</el-tag>
          </div> -->
        </template>
        <template #viewpoints>
          <div class="point-container">
            <div
              v-for="(item, index) in pointList"
              :key="index"
              class="point-row"
            >
              <span style="color: #666; margin-right: 10px">
                <span style="color: red">*</span>
                观点{{ index + 1 }} {{ detailId }}
              </span>
              <el-input
                v-model="pointList[index]"
                style="flex: 1; margin: 0 8px"
                maxlength="10"
                :disabled="detailId ? true : false"
                placeholder="请输入选项，不超过10个字"
              ></el-input>
              <el-button
                v-if="index > 1 && !detailId"
                type="text"
                @click="deletePoint(index)"
              >
                删除
              </el-button>
            </div>
            <span v-if="form.voteType === '2' && !detailId">
              <el-button
                icon="el-icon-plus"
                type="text"
                @click="addPoint"
              >
                添加观点
              </el-button>
              <span style="color: #999; font-size: 12px; margin-left: 20px">
                目前最多支持添加5个观点
              </span>
            </span>
          </div>
        </template>
        <!--关联话题-->
        <template #topic>
          <div>
            <el-button
              type="primary"
              @click="addTopic"
            >
              添加话题
            </el-button>
            <div>
              <el-tag
                v-for="tag in labels"
                :key="tag.id"
                closable
                class="tags-item"
                :class="[
                  form.labels.map((e) => e.id).includes(tag.id)
                    ? ''
                    : 'tagDisplay',
                ]"
                @close="handleClose(tag)"
              >
                {{ tag.name }}
              </el-tag>
            </div>
          </div>
        </template>
        <template #content>
          <HashtagTextArea
            ref="hashtag"
            :option="hashtagOption"
            :maxlength="2000"
            :account-type="accountType"
            :detail-type="form.type"
            @doInput="topicInput"
            @selectTopic="addTopic"
          ></HashtagTextArea>
          <!-- <div style="position: relative">
            <p
              class="p-text"
              :class="{ 'p-show': pShow }"
              @click="$refs.input.focus()"
              v-html="inputText2"
            /> -->
          <!-- <Mentionable
              :keys="['#']"
              :items="items"
              offset="16"
              insert-space
              style="position: absolute;z-index: 1;top:0;left:0"
              class="textarea-wrap"
              @open="loadIssues()"
              @apply="onApply"
            > -->
          <!-- <div
              style="position: absolute; z-index: 1; top: 0; left: 0"
              class="textarea-wrap"
            >
              <el-input
                ref="input"
                v-model="form.content"
                type="textarea"
                style="width: 660px"
                :autosize="{ minRows: 3 }"
                maxlength="2000"
                :show-word-limit="true"
                @focus="pShow = false"
                @input="textChange"
                @blur="textChangeColor(form.content)"
              /> -->
          <!-- <template #no-result>
                <div class="dim">
                  {{ issueLoading ? 'Loading...' : 'No result' }}
                </div>
              </template>

              <template #item-#="{ item }">
                <div
                  class="issue"
                >
                  <span class="number">
                    {{ item.name }}
                  </span>

                </div>
              </template> -->
          <!-- </Mentionable> -->
          <!-- </div> -->
          <!-- </div> -->
        </template>
      </avue-form>
      <template #footer>
        <el-button
          type="primary"
          :loading="loading"
          @click="submit"
        >
          发布
        </el-button>
        <el-button @click="visible = false">取消</el-button>
      </template>
    </el-dialog>
    <add-official-topic
      v-model="officialVisible"
      :labels="chooseLabel"
      title="添加话题"
      @getTopic="getTopic"
    ></add-official-topic>
  </div>
</template>
<script>
// import { Mentionable } from 'vue-mention';
import { dynamicOption } from '@/const/crud/community-content/dynamic';
import addOfficialTopic from './addOfficialTopic.vue';
import { remote } from '@/api/admin/dict';
import { addRules, selectDynamicById, updateRules } from '@/api/core/dynamic';
import { VOTE_STATUS, DYNAMIC_TYPE } from '@/const/type';
import { selectTopicList } from '@/api/core/topic';
import HashtagTextArea from './HashtagTextArea.vue';
import { getPhoneList } from '@/api/core/agreement';
// import { deepClone } from '@/util';
export default {
  components: {
    addOfficialTopic,
    // Mentionable,
    HashtagTextArea,
  },
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      form: {
        labels: [],
        tag: [],
        content: '',
        voteStatus: '0',
      },
      DYNAMIC_TYPE,
      loading: false,
      officialVisible: false,
      toggleList: [],
      chooseLabel: [],
      tagList: [],
      labels: [],
      fileWH: [],
      issueLoading: false,
      items: [],
      issues: [],
      topicList: [],
      inputText2: '',
      pShow: true,
      pointList: ['', ''],
      hashtagOption: {
        placeholder: '请输入',
      },
      startPosition: 0,
      endPosition: 0,
      hashtagContent: '',
      list: [],
      accountType: '',
    };
  },

  computed: {
    visible: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      },
    },
    detailId() {
      return this.editId;
    },
    formType() {
      if (this.detailId) {
        return 'edit';
      }
      return 'add';
    },
    dynamicOption() {
      return dynamicOption(
        this.formType === 'add' ? false : true,
        this.accountType ? this.accountType !== '2' : this.form.type !== '2'
      );
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.selectTag();
        if (this.detailId) {
          this.getDetail(this.detailId);
        } else {
          this.form = {
            labels: [],
            tag: [],
            content: '',
            voteStatus: '0',
            voteType: '2',
            voteResultType: '2',
          };
        }
        this.getLabels();
      } else {
        this.$refs.addform.resetFields();
        this.visible = false;
        this.form.labels = [];
        this.form.tag = [];
        this.form.type = '';
        this.form.title = '';
        this.form.image = [];
        this.form.voteTitle = '';
        this.form.voteDescription = '';
        this.form.voteEndTime = '';
        this.$refs.hashtag.replaceHashtagNodeContent('');
        this.form.voteStatus = '';
        this.toggleList = [];
        this.chooseLabel = [];
        this.accountType = '';
        this.pointList = ['', ''];
        this.inputText2 = '';
      }
    },
    toggleList: {
      handler(val) {
        this.form.tag = this.toggleList;
      },
      deep: true,
    },
    'form.voteType': {
      handler(val) {
        if (val === '1') {
          if (this.pointList.length > 2) {
            this.pointList = this.pointList.slice(0, 2);
          }
        }
      },
      deep: true,
    },
  },
  mounted() {
    this.getUserPhoneList();
  },
  methods: {
    //选择官方账号
    changeName(val) {
      const obj = this.list.find((item) => item.userId === val);
      if (obj.type === '0') {
        //官方
        this.accountType = DYNAMIC_TYPE.OFFICAL;
      } else {
        //基地
        this.accountType = DYNAMIC_TYPE.BASE;
      }
    },
    //关联账号
    async getUserPhoneList() {
      const res = await getPhoneList({
        type: '4',
      });
      this.list = res.data.data;
      this.list.forEach((el) => {
        el.label = `${el.nickname}（${el.phone}）`;
        el.value = el.userId;
      });
      console.log('list', this.list);
      // return res;
    },
    // mention方法
    // async loadIssues(searchText = null) {
    //   console.log(searchText);
    //   this.issueLoading = true;
    //   const res = await selectTopicList();
    //   this.issues = deepClone(res.data.data);
    //   this.issues.map(item => {
    //     item.value = `${item.name}#`;
    //   });
    //   this.items = this.issues;
    //   // this.items = await this.fetchIssues(searchText);
    //   this.issueLoading = false;
    // },
    // onApply (item, key, replacedWith) {
    //   console.log(item, key, `has been replaced with ${replacedWith}`);
    //   this.topicList.push(item);
    // },
    textChange(val) {
      this.inputText2 = val;
    },
    textChangeColor(val) {
      let replaceList = [];
      const reg = /#([^#]+)#/g;
      if (val.indexOf('#') !== -1) {
        replaceList = val.match(reg);
        for (let j = 0; j < replaceList.length; j++) {
          val = val.replaceAll(
            `${replaceList[j]}`,
            `<span style=\'color:#409eff;position:relative;z-index:10000;\'>${replaceList[j]}</span>`
          );
        }
      }
      this.inputText2 = val;
      this.pShow = true;
    },
    // fetchIssues (searchText = null) {
    //   return new Promise(resolve => {
    //     setTimeout(() => {
    //       if (!searchText) {
    //         resolve(this.issues);
    //       } else {
    //         selectTopicList({ name: searchText }).then(res => {
    //           resolve(res.data.data);
    //         });
    //       }
    //     }, 100);
    //   });
    // },
    async selectTag() {
      const res = await remote('article_tag');
      this.tagList = res.data.data;
    },
    uploadSizeError(error, limitedSize) {
      // console.log(134, error, limitedSize);
      if (error === '文件太大不符合') {
        this.$message.warning(
          `文件大小不能超过${limitedSize.fileSize / 1024}M`
        );
      }
    },
    uploadExceed(limit, files, fileList, column) {
      this.$message.error(`只能上传${limit}个文件`);
    },
    async uploadBefore(file, done, loading, column) {
      console.log('fff', file);
      const isType =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif' ||
        file.type === 'image/bmp' ||
        file.type === 'image/jpg' ||
        file.type === 'image/mpeg' ||
        file.type === 'video/WMV' ||
        file.type === 'video/quicktime' ||
        file.type === 'video/mp4' ||
        file.type === 'image/webp';
      if (!isType) {
        loading();
        this.$message.error('上传格式不对!');
      }
      const flag = await this.getMp4Time(file);
      if (!flag) {
        loading();
        this.$message.warning('上传视频时长在三分钟以内！');
      }
      const that = this;
      // 计算他的宽高
      this.imgchecked(file).then((data) => {
        //data返回值即为判断结果。
        that.fileWH.push({
          uid: file.uid,
          url: file.name,
          width: data.width,
          height: data.height,
        });
        done();
      });
      return isType && flag;
    },
    //判断尺寸方法
    imgchecked(file) {
      return new Promise((resolve, reject) => {
        if (file.type.indexOf('image') !== -1) {
          //上传文件为图片类型
          const img = new Image();
          img.onload = function () {
            resolve(img);
          };
          img.src = URL.createObjectURL(file);
        } else {
          //上传文件为视频类型
          var videoUrl = URL.createObjectURL(file);
          var videoObj = document.createElement('video');
          videoObj.onloadedmetadata = function (evt) {
            URL.revokeObjectURL(videoUrl);
            videoObj.width = videoObj.videoWidth;
            videoObj.height = videoObj.videoHeight;
            // 执行上传的方法，获取外网路径，上传进度等
            resolve(videoObj);
          };
          videoObj.src = videoUrl;
          videoObj.load();
        }
      });
    },
    getMp4Time(file) {
      return new Promise((resolve) => {
        const fileExtend = file.name
          .substring(file.name.lastIndexOf('.'))
          .toLowerCase();
        //如果是mp4
        if (
          fileExtend === '.mp4' ||
          fileExtend === '.mpeg' ||
          fileExtend === '.WMV' ||
          fileExtend === '.mov'
        ) {
          //把element上传组件传给我们的file转成url
          const url = URL.createObjectURL(file);
          //获取mp4对象
          const v = document.createElement('video');
          v.src = url;
          //监听事件
          v.addEventListener('loadedmetadata', () => {
            //时间
            const time = Math.ceil(v.duration * 100) / 100;
            console.log('time', time, v.videoWidth, v.videoHeight);
            this.width = v.videoWidth;
            this.height = v.videoHeight;
            if (time > 4 * 60) {
              console.log('进来了码');
              resolve(false);
            } else {
              resolve(true);
            }
          });
        } else {
          //不是mp4
          resolve(true);
        }
      });
    },
    select(v) {
      const ind = this.toggleList.findIndex((el) => el.id === v.id);
      if (ind > -1) {
        this.toggleList.splice(ind, 1);
      } else {
        this.toggleList.push(v);
      }
    },
    //添加话题
    addTopic() {
      this.officialVisible = true;
    },
    async getLabels() {
      const res = await selectTopicList();
      this.labels = res.data.data;
    },
    //添加话题
    addPoint() {
      if (this.pointList.length < 5) {
        this.pointList.push('');
        return;
      }
      this.$message.warning('目前最多支持添加5个观点');
    },
    //删除话题
    deletePoint(index) {
      this.pointList.splice(index, 1);
    },
    getTopic(data) {
      console.log(data);
      this.chooseLabel = data;
      let hashtag = '';
      data.forEach((element) => {
        hashtag += `#${element.name}#`;
      });
      const startStr = this.form.content.substring(0, this.startPosition);
      const endStr = this.form.content.substring(
        this.startPosition,
        this.endPosition
      );
      this.form.content = `${startStr}${hashtag}${endStr}`;
      this.$refs.hashtag.replaceHashtagNodeContent(this.form.content);
    },
    topicInput(value, inputType, inputChar, startPos, endPos) {
      this.form.content = value;
      this.startPosition = startPos;
      this.endPosition = endPos;
    },
    getDetail() {
      selectDynamicById(this.detailId).then((res) => {
        this.form = res.data.data;
        this.form.name = res.data.data.userId;
        if (res.data.data.labelIds) {
          this.form.tag = JSON.parse(res.data.data.labelIds).map((item) => {
            return { id: item };
          });
        }
        if (res.data.data.files) {
          this.form.image = JSON.parse(res.data.data.files).map((item) => {
            let type = 'mov';
            if (item.type === 'image') {
              type = 'jpg';
            }
            return {
              ...item,
              url: `${item.url}?.${type}`,
            };
          });
        }
        this.form.content = res.data.data.content;
        this.pointList = [];
        if (res.data.data.sharePkList) {
          res.data.data.sharePkList.forEach((ele) => {
            this.pointList.push(ele.point);
          });
        }
        this.textChange(this.form.content);
        this.toggleList = this.form.tag;
        console.log('this.form', this.form.voteStatus);
        if (!res.data.data.voteStatus) {
          this.form.voteStatus = VOTE_STATUS.NO;
        }

        this.$refs.hashtag.replaceHashtagNodeContent(this.form.content);
      });
    },
    transForm(arr) {
      const target = arr.map((el) => {
        // 针对已经处理过的数据，不再进行处理
        if (typeof el === 'string') {
          el = {
            url: el,
          };
        }
        if (el.type) {
          return el;
        }
        const suffix = el.url.substr(el.url.lastIndexOf('.') + 1).toLowerCase();
        let type = '';
        let poster = '';
        const imgSuffix = ['jpg', 'png', 'jpeg', 'webp', 'heic'];
        if (imgSuffix.includes(suffix)) {
          type = 'image';
          poster = el.url;
        } else {
          type = 'video';
          poster = `${el.url}?vframe/jpg/offset/0`;
        }
        //获取在上传前记录的宽、高
        const file =
          this.fileWH.find((item) => {
            return el.url.indexOf(item.uid + item.url) !== -1;
          }) || {};
        return {
          fileName: '',
          url: el.url,
          type,
          poster,
          width: el.width || file.width || 0,
          height: el.width || file.height || 0,
        };
      });
      return target;
    },
    //发布
    submit() {
      this.$refs['addform'].validate(async (valid, done) => {
        if (valid) {
          this.loading = true;
          const attr = this.form.image.map((item) => {
            if (typeof item === 'string') {
              item = {
                url: item,
              };
            }
            return {
              ...item,
              url: item.url.replace(/\?.*$/, ''),
            };
          });
          console.log(attr);
          const target = await this.transForm(attr);
          const params = {
            userId: this.form.name,
            content: this.form.content,
            type: this.accountType,
            title: this.form.title,
            // coverImage:`${attr[0]}?vframe/jpg/offset/0`
          };
          params.coverImage = `${target[0].poster}`;
          if (target) {
            params.files = JSON.stringify(target);
          }
          if (this.form.tag && this.form.tag.length) {
            params.labelIds = JSON.stringify(
              this.form.tag.map((item) => item.id)
            );
          }

          if (
            this.form.voteStatus === '1' &&
            this.accountType !== DYNAMIC_TYPE.BASE
          ) {
            let pointIndex = -1;
            for (let i = 0; i < this.pointList.length; i++) {
              if (!this.pointList[i]) {
                pointIndex = i;
                break;
              }
            }
            if (pointIndex > -1) {
              this.$message.warning(`观点不能为空`);
              this.loading = false;
              done();
              return;
            }
            params.voteStatus = this.form.voteStatus;
            params.voteTitle = this.form.voteTitle;
            params.voteType = this.form.voteType;
            params.voteResultType = this.form.voteResultType;
            params.voteEndTime = this.form.voteEndTime;
            params.voteDescription = this.form.voteDescription;
            params.pointList = this.pointList;
          } else {
            delete params.voteTitle;
            delete params.voteType;
            delete params.voteEndTime;
            delete params.voteDescription;
            delete params.viewpoints;
          }
          // if (this.labels && this.labels.length) {
          //   const content = this.form.content.split('#');
          //   for (const item in this.labels) {
          //     if (content.includes(this.labels[item].name)) {
          //       this.form.labels.push(this.labels[item].id);
          //     }
          //   }
          //   params.topicIds = JSON.stringify(this.form.labels);
          // }
          if (this.formType === 'add') {
            await addRules(params)
              .then(() => {
                this.loading = false;
                done();
              })
              .catch((err) => {
                this.loading = false;
                done();
                throw new Error(err);
              });
          } else {
            params.id = this.detailId;
            params.type = this.accountType ? this.accountType : this.form.type;
            params.voteStatus = this.form.voteStatus;
            await updateRules(params)
              .then(() => {
                this.loading = false;
                done();
              })
              .catch((err) => {
                this.loading = false;
                done();
                throw new Error(err);
              });
          }
          this.$refs.addform.resetFields();
          this.visible = false;
          this.$emit('refresh');
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.sub-item {
  margin-top: 20px;
  margin-right: 12px;
  border: 1px solid #6e6b6b;
  padding: 3px 7px;
  cursor: pointer;
  box-sizing: border-box;
  color: #6e6b6b;
  &.selected {
    background: $--color-primary;
    color: #fff;
    border: 1px solid $--color-primary;
  }
}
// .tags-item {
//   span {
//     margin-top: 20px;
//     margin-right: 12px;
//     border: 1px solid #848080;
//     padding: 3px 7px;
//     cursor: pointer;
//     box-sizing: border-box;
//     color: #848080;
//     border-radius: 5px;
//     &.selected {
//       background: $--color-primary;
//       color: #fff;
//       border: 1px solid $--color-primary;
//     }
//   }
// }
.tagDisplay {
  display: none;
}
.mention-item {
  z-index: 2211 !important;
}
.textarea-wrap .el-textarea__inner {
  color: rgba(0, 0, 0, 1);
  padding: 8px;
  caret-color: black;
  background: transparent;
  font-size: 16px;
}
.p-text {
  width: 660px;
  padding: 6px 16px;
  white-space: pre-wrap;
  margin: 0;
  font-size: 13px;
  box-sizing: border-box;
  line-height: 32px;
  line-height: 1.5;
  visibility: hidden;
}
.p-show {
  visibility: visible;
}
</style>
<style lang="scss">
.tooltip {
  z-index: 2111 !important;
  padding: 4px 10px;
  border-radius: 4px;
  background: #f7f7f7;
  .tooltip-arrow {
    z-index: 21111 !important;
    position: absolute !important;
  }
}
.mention-selected {
  background: rgb(192, 250, 153);
}
.point-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 10px;
}
</style>
